package com.jiang.interceptor;

import java.lang.reflect.Field;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jiang.utils.ValidateUtils;

public class DataValidateInterceptor implements HandlerInterceptor {

	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object hamobj) throws Exception {
		
		boolean flag = true;
		// 1. 强转类型
		HandlerMethod ham = (HandlerMethod) hamobj;
		// 2. 打印各种信息
		System.out.println(ham.getBean());// 获取Action对象
		System.out.println(ham.getBeanType()); // 获取Action对象类型
		System.out.println(ham.getMethod().getName()); // 获取拦截到的方法
		//3. 获取验证规则
		String rule_name = ham.getMethod().getName()+"_"+"rule";
		Field field = ham.getBean().getClass().getDeclaredField(rule_name);
		if(field!=null){
			String rule_value = field.get(ham.getBean()).toString();
			// 直接获取验证规则中的数值比较
			String rulesStr[] = rule_value.split("\\|");
			for (String eachRule : rulesStr){
				String ruleName = eachRule.split(":")[0];
				String type = eachRule.split(":")[1];
				String param_value = request.getParameter(ruleName);
				// 比较值与类型是否匹配
				flag = ValidateUtils.validateRule(param_value, type);
				if(!flag){
					break;
				}
			}
			System.out.println("验证是否通过:" + flag);
		}
		return flag;
	}
	
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}



}
